//分拣框设置
import { useState, useEffect } from "react";
import { Form, InputNumber, message, Radio } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { querySortingboxconfig, sortingboxconfigSave, sortingboxconfigUpdate } from "../../service";
import CommonLoading from "@/components/CommonLoading";
import { isEmpty } from "lodash";

const SortConfigModal = ({ visible, handleOk, handleCancel }) => {
	const [configData, setConfigData] = useState({});
	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	const uniqueCodeOccupyValue = Form.useWatch("uniqueCodeOccupy", form);

	useEffect(() => {
		if (visible) {
			form.resetFields();
			getSortingboxconfig();
		}
	}, [visible]);

	useEffect(() => {
		if (!isEmpty(configData)) {
			form.resetFields();
		}
	}, [configData]);

	//获取配置详情
	const getSortingboxconfig = async () => {
		setLoading(true);
		const { success, data = {} } = await querySortingboxconfig();
		if (success) {
			setConfigData(data);
		}
		setLoading(false);
	};

	//保存配置详情
	const handSortingboxconfigSave = async val => {
		setLoading(true);
		let res;
		if (isEmpty(configData)) {
			res = await sortingboxconfigSave(val);
		} else {
			res = await sortingboxconfigUpdate({ ...val, id: configData.id });
		}
		const { success, msg = "" } = res;
		if (success) {
			// getSortingboxconfig();
			message.success(msg);
			handleCancel();
		}
		setLoading(false);
	};

	const onOk = () => {
		form.validateFields().then(async value => {
			handSortingboxconfigSave(value);
		});
	};
	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};

	return (
		<CommonModal title={{ title: "分拣框设置" }} visible={true} onOk={onOk} onCancel={onCancel} minHeight="150px">
			<Form
				form={form}
				initialValues={{
					uniqueCodeOccupy: (configData.uniqueCodeOccupy || configData.uniqueCodeOccupy == 0) ? configData.uniqueCodeOccupy : 1,
					maxBoxOrderNum: (configData.maxBoxOrderNum || configData.maxBoxOrderNum == 0) ? configData.maxBoxOrderNum : 1,
				}}
				name="mark-unuaual-modal"
			>
				<Form.Item
					label="生成唯一码时自动预占用分拣框："
					name="uniqueCodeOccupy"
					labelCol={{
						span: 12
					}}
				>
					<Radio.Group>
						<Radio value={1}>是</Radio>
						<Radio value={0}>否</Radio>
					</Radio.Group>
				</Form.Item>
				{uniqueCodeOccupyValue == 1 ? (
					<Form.Item
						label="一个分拣框允许占用的最大订单数："
						name="maxBoxOrderNum"
						labelCol={{
							span: 12
						}}
					>
						<InputNumber min={0} precision={0} />
					</Form.Item>
				) : (
					""
				)}
			</Form>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default SortConfigModal;
